package com.senseuni.da.ui.views

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.senseuni.da.R

class SettingItemView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : FrameLayout(context, attrs, defStyleAttr, defStyleRes) {

    private val iconImageView: ImageView
    private val titleLabel: TextView
    private val summaryLabel: TextView

    init {
        // 初始化布局
        inflate(context, R.layout.layout_setting_item_view, this)

        // 获取子视图
        iconImageView = findViewById(R.id.iv_icon)
        titleLabel = findViewById(R.id.tv_title)
        summaryLabel = findViewById(R.id.tv_summary)

        // 解析自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SettingItemView, defStyleAttr, defStyleRes)
        val iconResId = typedArray.getResourceId(R.styleable.SettingItemView_sivIcon, R.drawable.ic_my_friend)
        val titleText = typedArray.getString(R.styleable.SettingItemView_sivTitle) ?: ""
        val summaryText = typedArray.getString(R.styleable.SettingItemView_sivSummary) ?: ""
        val titleColor = typedArray.getColor(R.styleable.SettingItemView_sivTitleColor, ContextCompat.getColor(context, R.color.color_title))
        val summaryColor = typedArray.getColor(R.styleable.SettingItemView_sivSummaryColor, ContextCompat.getColor(context, R.color.color_summary))

        // 设置属性
        iconImageView.setImageResource(iconResId)
        titleLabel.text = titleText
        summaryLabel.text = summaryText
        titleLabel.setTextColor(titleColor)
        summaryLabel.setTextColor(summaryColor)

        // 回收 TypedArray
        typedArray.recycle()
    }

    fun setIconResource(resId: Int) {
        iconImageView.setImageResource(resId)
    }

    fun setTitle(text: String) {
        titleLabel.text = text
    }

    fun setTitle(resId: Int) {
        titleLabel.text = context.getString(resId)
    }

    fun setSummary(text: String) {
        summaryLabel.text = text
    }

    fun setSummary(resId: Int) {
        summaryLabel.text = context.getString(resId)
    }

    fun getSummary():String {
        return summaryLabel.text.toString()
    }

    fun setTitleColor(color: Int) {
        titleLabel.setTextColor(color)
    }

    fun setSummaryColor(color: Int) {
        summaryLabel.setTextColor(color)
    }
}
